package com.ubs.training.server.dao.impl.hbm;

import com.googlecode.flyway.core.migration.sql.SqlStatement;
import com.ubs.training.server.dao.ContactDao;
import com.ubs.training.server.dao.model.Client;
import com.ubs.training.server.dao.model.Contact;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import javax.persistence.criteria.From;
import java.util.List;
import org.springframework.stereotype.Repository;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/27/12
 * Time: 3:17 AM
 * To change this template use File | Settings | File Templates.
 */
@Repository("hbmContactDao")
public class HbmContactDao implements ContactDao {

    private SessionFactory factory;

    private HibernateTemplate tpl;
    private BasicDataSource ds;

    public SessionFactory getFactory() {
        return factory;
    }

    @Autowired
    public void setFactory(SessionFactory factory) {
        tpl = new HibernateTemplate(factory);
        this.factory = factory;
    }

    @Override
    public List<Contact> getAll() {
        System.out.println("INVOKED HIBERNATE PART! _________________---------------------------------------");
        return tpl.loadAll(Contact.class);
    }

    @Override
    public List<Contact> getAllContactsOfClient(int id) {
        return tpl.findByCriteria(DetachedCriteria.forClass(Contact.class).add(Property.forName("clientID").eq(id)));
    }

    @Override
    public List<Contact> getAllContactsOfClient(Client cl) {
        return tpl.findByCriteria(DetachedCriteria.forClass(Contact.class).add(Property.forName("clientID").eq(cl.getId())));
    }

    @Override
    public Contact getContactByID(int id) {
        return tpl.load(Contact.class, id);
    }

    @Override
    public void add(Contact cont) {
        tpl.saveOrUpdate(cont);
    }

    @Override
    public void update(Contact cont) {
        tpl.save(cont);
    }

    @Override
    public void removeContact(Contact cont) {
        tpl.delete(cont);
    }

    @Override
    public void removeContact(int id) {
        String hql = "delete * from contact where contactID=" + id;
        Query query=tpl.getSessionFactory().getCurrentSession().createQuery(hql);
        query.executeUpdate();
    }

    public void setDs(BasicDataSource ds) {
        this.ds = ds;
    }

    public BasicDataSource getDs() {
        return ds;
    }
}